package ldh.serialize.type;

import ldh.serialize.BinarySerialized;
import ldh.serialize.Serialized;
import ldh.serialize.SerializedConfig;
import ldh.serialize.SerializedItem;
import ldh.serialize.io.ByteBuf;
import ldh.serialize.util.ClassInfo;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ldh on 2016/11/19.
 */
public class MethodParamSerialized implements BinarySerialized<Object> {

    public Method method;

    public MethodParamSerialized(Method method) {
        this.method = method;
    }

    @Override
    public void write(ByteBuf out, Object m) throws IOException {
        Class[] classes = method.getParameterTypes();
        if (classes != null && classes.length > 0) {
            Object[] params = (Object[]) m;
            int i = 0;
            for (Class clazz : classes) {
                List<SerializedItem> items = SerializedConfig.getSerializeItems(clazz);
                Object obj = params[i++];
                for (SerializedItem si : items) {
                    si.write(out, obj);
                }
            }
        }
    }

    @Override
    public Object read(ByteBuf in) throws IOException {
        Class[] classes = method.getParameterTypes();
        if (classes != null && classes.length > 0) {
            Object[] params = new Object[classes.length];
            int i=0;
            for (Class clazz : classes) {
                Object param = ClassInfo.newClazz(clazz);
                params[i] = param;
                List<SerializedItem> items = SerializedConfig.getSerializeItems(clazz);
                for (SerializedItem si : items) {
                    Object o = si.read(param, in);
                    if (param == null) {
                        params[i] = o;
                    }
                }
                i++;
            }
            return params;
        }
        return null;
    }

    @Override
    public Class<Object> getClassType() {
        return null;
    }
}
